package com.laogao.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laogao.dto.ExamDto;
import com.laogao.entity.Exam;
import com.laogao.entity.Question;
import com.laogao.entity.SelectOptions;
import com.laogao.mapper.ExamMapper;
import com.laogao.service.ExamService;
import com.laogao.service.OptionService;
import com.laogao.service.QuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ExamServiceImpl1 extends ServiceImpl<ExamMapper, Exam> implements ExamService {


    private final ExamMapper examMapper;
    private final QuestionService questionService;
    private final OptionService optionService;

    private static final int BATCH_SIZE = 1000;

    @Transactional(rollbackFor = Exception.class)
    public void saveExamWithAll(ExamDto examDto, int questionCount, int optionCountPerQuestion) {
        // 预先生成试卷 ID
        Exam exam = new Exam();
        String examId = IdUtil.getSnowflakeNextIdStr();
        exam.setId(examId);
        exam.setName(examDto.getName());
        examMapper.insert(exam);

        List<Question> questionList = new ArrayList<>();
        List<SelectOptions> allSelectOptionsList = new ArrayList<>();

        for (int i = 0; i < questionCount; i++) {
            // 预先生成题目 ID
            String questionId = IdUtil.getSnowflakeNextIdStr();
            Question question = new Question();
            question.setId(questionId);
            question.setExamId(examId);
            question.setContent("题目内容" + i);
            questionList.add(question);

            // 构建选项数据
            for (int j = 0; j < optionCountPerQuestion; j++) {
                SelectOptions selectOptions = new SelectOptions();
                selectOptions.setId(IdUtil.getSnowflakeNextIdStr());
                selectOptions.setQuestionId(questionId);
                selectOptions.setContent("选项内容" + j);
                allSelectOptionsList.add(selectOptions);
            }
        }

        // 批量插入题目和选项
        questionService.saveBatch(questionList, BATCH_SIZE);
        optionService.saveBatch(allSelectOptionsList, BATCH_SIZE);
    }
}